import {SocketEventType, WebsocketService} from "../type";
import {MsgType} from "../constants";
import {getDataType} from "../utils";
import EventEmitter from '../event/eventEmitter';


export class SocketEvent implements SocketEventType {
    openEventStack: Array<Function> = [];
    msgEmitter:EventEmitter;
    paramsList:Array<any> = [];
    public constructor(protected socket: WebsocketService) {
        this.msgEmitter = new EventEmitter();
        this.msgEmitter.on("message",this.callMethod.bind(this));
    }

    open() {
        console.info('【webSocket】连接成功');
        this.socket.heartCheck.start();
        this.openEventStack.filter(i => typeof i == 'function').forEach(i => i.call(this))
    }

    onOpen() {
        return new Promise(resolve => {
            this.openEventStack.push(resolve);
        })
    }

    error(e) {
        console.warn('【websocket】连接发生错误:', e);
        this.socket.reconnect();
    }

     message<T>(e) {
        // 解析消息
        let json;
        try {
            json = JSON.parse(e.data);
        } catch (e: any) {
            console.warn('【websocket】收到无法解析的消息:', e.data);
            return;
        }
        let type = json[MsgType.TYPE];
        switch (type) {
            case MsgType.TYPE_HB:
                //心跳检测
                this.socket.heartCheck.back();
                break;
            case MsgType.CALL_METHOD:
                this.paramsList.push(json);
                this.msgEmitter.emit("message",json);
                break;
            case MsgType.BATCH_CALL_METHOD:
                let methodList = json[MsgType.METHOD_LIST];
                if (methodList && getDataType(methodList, "arr")) {
                    for (let cJson of methodList) {
                        try {
                            this.paramsList.push(cJson);
                            this.msgEmitter.emit("message",cJson);
                        } catch (e) {
                            console.warn('【websocket】callMethod error', cJson, e);
                        }
                    }
                }
                break;
            default:
                console.warn('【websocket】收到不识别的消息类型:' + type);
                break;
        }
    }

    callMethod() {
        let json:any = this.paramsList.shift();
        if(getDataType(json, "arr")){
            return;
        }
        let data = json[MsgType.DATA];
        let methodId = json[MsgType.METHOD_ID];
        let callStatus = json[MsgType.CALL_STATUS];
        let methodName = json[MsgType.METHOD_NAME];

        let msg = json[MsgType.MSG_TXT];
        if ('ok' != callStatus) {
            this.socket.doError(methodId, methodName, msg);
        } else {
            this.socket.doSuccess(methodId, methodName, data);
        }
    }

    close(e) {
        console.info('【websocket】连接被关闭:', e);
        this.socket.reconnect();
    }
}
